#!/bin/bash

set -o errexit -o nounset -o pipefail
set -o xtrace

# Calls CMake to generate build files and then run the build.
# Usage:
#   generate_and_build <output directory> [<other generate args> ...]
generate_and_build() {
  local folder_name=$1
  shift

  mkdir "${folder_name}"
  cmake "$@" -B "${folder_name}" .
  cmake --build "${folder_name}" --parallel
}

if [[ "${TRAVIS_OS_NAME}" == "linux" ]]; then
  # Update package lists first. Without this, we've seen missing packages
  # and dependency conflicts that block installation.
  sudo apt-get update

  # Try to install kernel headers. Continue on failure, e.g. when running in
  # an LXD container where Ubuntu has no headers package corresponding to the
  # host kernel. In that case the kernel modules won't be built.
  sudo apt-get install "linux-headers-$(uname -r)" || true
fi

OS_COMPILER_CPU=${TRAVIS_OS_NAME}_${TRAVIS_COMPILER}_${TRAVIS_CPU_ARCH}
case "${OS_COMPILER_CPU}" in
  linux_clang_*)
    generate_and_build build -DCMAKE_CXX_CLANG_TIDY=clang-tidy
    ;;

  windows_*)
    generate_and_build build-x64 -A x64
    generate_and_build build-win32 -A Win32
    ;;

  linux_gcc_amd64)
    # Install the 32-bit compiler and C/C++ runtimes
    sudo apt-get install \
        g++-i686-linux-gnu \
        libc6-i386 \
        lib32stdc++6

    generate_and_build build-x86_64
    generate_and_build build-i686 \
        -DCMAKE_TOOLCHAIN_FILE=ci/toolchains/i686-linux-gnu.cmake
    ;;

  linux_gcc_*|osx_clang_*)
    generate_and_build build
    ;;
  
  *)
    >&2 echo Missing build commands for "${OS_COMPILER_CPU}"
    exit 1
    ;;
esac
